package com.tanhua.dubbo.api;


import com.tanhua.model.mongo.PBVoice;
import com.tanhua.model.vo.VoiceVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 桃花传音服务接口类
 */
@DubboService
public class PBVoiceApiimpl implements PBVoiceApi {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserLocationApi userLocationApi;
    @Autowired
    private VoiceFunctionApi voiceFunctionApi;

    /**
     * 桃花传音--发送语音
     *
     * @param voiceUrl
     * @param age
     * @param gender
     * @param userId
     */
    @Override
    public void saveVoice(String voiceUrl, Integer age, String gender, Long userId) {
        //获取地理位置
        GeoJsonPoint geoJsonPoint = userLocationApi.findLocation(userId);
        if (geoJsonPoint==null){
            geoJsonPoint = new GeoJsonPoint(133.11,12.11);
        }
        PBVoice pbVoice = new PBVoice();
        pbVoice.setSoundUrl(voiceUrl);
        pbVoice.setAge(age);
        pbVoice.setUserId(userId.intValue());
        pbVoice.setGender(gender);
        pbVoice.setId(ObjectId.get());
        pbVoice.setLocation(geoJsonPoint);
        mongoTemplate.insert(pbVoice);
    }

    /**
     * 桃花传音--接收语音
     *
     * @param gender
     * @param age
     * @param userId
     * @param objectIdList
     * @return
     */
    @Override
    public VoiceVo findPBVoice(String gender, Integer age, Long userId, List<ObjectId> objectIdList) {
        GeoJsonPoint location = userLocationApi.findLocation(userId);//取地址

        //判断性别，只查异性
        if (gender.equals("man")) {
            gender = "woman";
        } else if (gender.equals("woman")) {
            gender = "man";
        }
        //根据当前用户位置 和 距离 搜索附近的用户
        Circle circle = new Circle(location, 30000);
        //根据条件查询
        Query query = new Query();
        query.addCriteria(Criteria.where("gender").is(gender).and("age").gte(age - 5).lte(age + 5).and("location").withinSphere(circle).and("id").nin(objectIdList));//性别、年龄的要求//根据当前用户位置 和 距离 搜索附近的用户//排除已看过
        PBVoice pbVoice = mongoTemplate.findOne(query, PBVoice.class);
        if (pbVoice==null){
            return null;
        }
        //封装返回页面的数据类型
        VoiceVo vo = new VoiceVo();
        BeanUtils.copyProperties(pbVoice,vo);//gender age soundUrl
        vo.setId(pbVoice.getUserId());


        //添加已接收表
        voiceFunctionApi.saveVoiceUser(userId.intValue(),pbVoice.getId());

        return vo;
    }
}